<?php
 if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Nota_venta extends CI_Controller {
	
	
	private $oModNotaVenta;
	private $oComun;
	private $pdf;
	private $oHtml2Pdf;
	private $oCustomerModel;
	private $oCommonModel;
	private $oServices;
	private $oMoService;
	
	function __construct(){
		parent::__construct();
		$this->load->library('valida_sesion');
		$this->load->model('customer_model','CustomerModel');
		$this->load->helper(array('form', 'url'));
        //$this->load->model('nota_venta_model','notaVentaModel');
		$this->load->library('form_validation');
		$this->oModNotaVenta = new Nota_venta_model();
		//$this->oCommon = new common();
		$this->oComun = new Comunes();
		//$this->pdf =  new Pdf();
		//$this->oHtml2Pdf = new Html2Pdf();
		$this->oCustomerModel = new customer_model();
		$this->oCommonModel = new Common_model();
		$this->oMoService =  new service_model(); 
		
	}

	
	public function testPage(){
		$this->load->view('admin/testPage');
	}
	

    public function index(){
      	$iCorrelativo = $this->oModNotaVenta->getCorrelative();
  		$this->load->view('admin/notaVentaView3',array('iCorrelativo'=>$iCorrelativo));
    }

    
    public function process(){
    	
		$aData = Array();

    	$this->form_validation->set_rules('cli_id_cliente', 'cli_id_cliente', 'trim|required|xss_clean');
    	$this->form_validation->set_rules('tse_id_tiposervicios[]', 'tse_id_tiposervicios', 'trim|required|xss_clean');
    	$this->form_validation->set_rules('valor_uf[]', 'valor_uf', 'trim|required|xss_clean');
    	$this->form_validation->set_rules('valor_pesos[]', 'valor_pesos', 'trim|required|xss_clean');
    	$this->form_validation->set_rules('cli_id_cliente', 'cli_id_cliente', 'trim|required|xss_clean');
    	$this->form_validation->set_rules('cli_id_cliente', 'cli_id_cliente', 'trim|required|xss_clean');
    	
    	if($this->form_validation->run() === FALSE){
    		$oMensaje = $this->oComun->getMessageError('Faltaron datos que ingresar');
    		$this->session->set_flashdata('sMsg',$oMensaje);
    		$iCorrelativo = $this->oModNotaVenta->getCorrelative();
			$this->load->view('admin/notaVentaView3',array('iCorrelativo'=>$iCorrelativo,'sMsg'=>$oMensaje));
    	}
    	else{
     		
    		$aData['aNotaVenta']['cli_id_cliente'] =  $this->input->post('cli_id_cliente');
    		$aData['aNotaVenta']['not_totalprecio_uf'] =  $this->input->post('not_totalprecio_uf');
    		$aData['aNotaVenta']['not_totalprecio_pesos'] =  $this->input->post('not_totalprecio_pesos');
    		$aData['aNotaVenta']['not_observaciones'] =  $this->input->post('observaciones');
    		$aData['aNotaVenta']['recepcionador'] =  $this->input->post('recepcionador');
    		$aData['aNotaVenta']['not_correlativoconvenio'] =  $this->input->post('not_correlativoconvenio');
    		$aData['aServices']['tse_id_tiposervicios'] =  $this->input->post('tse_id_tiposervicios');
    		$aData['aServices']['valor_uf'] =  $this->input->post('valor_uf');
    		$aData['aServices']['valor_pesos'] =  $this->input->post('valor_pesos');
    		$aData['aServices']['cantidad_visitas'] =  $this->input->post('cantidad_visitas');
    		$aData['aServices']['tipo_convenio'] =  $this->input->post('tipo_convenio');
    		
    		$aData['aServices']['for_id_formapago'] =  $this->input->post('forma_pago');
    		
    		// guardamos la nota venta
    		$aRetorno = $this->oModNotaVenta->guardaNotaVenta($aData);
    		
			if ($aRetorno){
				
				$aData['aServices']['not_id_notaventa'] = $this->db->insert_id();
				// guardamos el servicio
				$aRetService = $this->oMoService->guardarServicio($aData);
				if(!$aRetService)
					$aRetorno['retorno'] = 'Error al almacenar los datos';
						
// 				print_r($aData);exit();
				
			}
    		
    		// creamos las visitas
    		//$aRetorno  = $this->oMoService->creaVisitas($aData);
    		
    		if($aRetorno['retorno'] == ''){
    			$oMensaje = $this->oComun->getMessageSuccessfully('Nota de venta agregada con exito');
    			//cramos el pdf
    			$this->creaPdfNotaVenta($aData);
    			
    			$this->session->set_flashdata('sMsg',$oMensaje);
			}else{
				$oMensaje = $this->oComun->getMessageError('Ha ocurrido un error al ingresar los datos');
				$this->session->set_flashdata('sMsg',$oMensaje);
			}
			$iCorrelativo = $this->oModNotaVenta->getCorrelative();
			$this->load->view('admin/notaVentaView3',array('iCorrelativo'=>$iCorrelativo,'sMsg'=>$oMensaje));
    	}
    	
    }

    public function creaPdfNotaVenta($aData){
    	
    	$aCliente = $this->oCustomerModel->getCustomer($aData['aNotaVenta']['cli_id_cliente']);
     	$oDom = new DOMDocument("1.0","UTF-8");
     	$oDom->loadHTMLFile('application/views/plantillas/notaventaPDF.html');
     	
     	$sFecha = '';
     	$oTable = $oDom->getElementById('notaservicio');
     	$sFecha =  date("d-m-Y");
     	$oDom->getElementById('fechanota')->appendChild($oDom->createTextNode('FECHA: '.$sFecha));
     	$oDom->getElementById('nombre')->appendChild($oDom->createTextNode('SEÑOR(ES) '.$aCliente['sNombre']));
     	$oDom->getElementById('direccion')->appendChild($oDom->createTextNode('DIRECCI&Oacute;N(ES) '.$aCliente['sDCliente']));
     	$oDom->getElementById('fono')->appendChild($oDom->createTextNode('FONO: '.$aCliente['sTelefono']));
     	$oDom->getElementById('rut')->appendChild($oDom->createTextNode('RUT: '.$aCliente['sRut']));
     	$oDom->getElementById('giro')->appendChild($oDom->createTextNode('GIRO: '.$aCliente['sGiro']));
    
     	
     	
     	$aServicios = $this->oCommonModel->getTypeService();
     	
     	
     	$i = 0;
     	foreach($aData['aServices']['services'] as $aService){
     		$tr = $oDom->createElement('tr');
     		$oTable->appendChild($tr);
     		$td1 = $oDom->createElement('td');
     		$td2 = $oDom->createElement('td');
     		$td3 = $oDom->createElement('td');
     		if(isset($aServicios[$aService-1])) 
     			$td1->appendChild($oDom->createTextNode($aServicios[$aService-1]['tse_descripcion']));
     		$td2->appendChild($oDom->createTextNode($aData['aServices']['valor_uf'][$i]));
     		$td3->appendChild($oDom->createTextNode($aData['aServices']['valor_pesos'][$i]));
     		$tr->appendChild($td1);
     		$tr->appendChild($td2);
     		$tr->appendChild($td3);
     		$i++;
     	}
     	if(isset($aServicios[$aService-1]))
     		$oDom->createTextNode($aServicios[$aService-1]['tse_descripcion']);
     	$oDom->getElementById('observaciones')->appendChild($oDom->createTextNode($aData['aNotaVenta']['not_observaciones']));
     	$this->ImprimePDF($oDom->saveHTML(),$aData['aNotaVenta']['not_correlativoconvenio']);
    }
    
    function ImprimePDF($html='', $iCorrelativo, $stream=TRUE) {
    		 
    		$filename = 'Notaventa_'.$iCorrelativo.".pdf";
		    $this->load->helper(array('dompdf', 'file'));
		    pdf_create($html, $filename);
 		    $enlace = base_url()."tmp/Notaventa_".$iCorrelativo.".pdf";
 		    echo '<script type="text/javascript" language="javascript">
			window.open("'.$enlace .'","Notaventa numero: '.$iCorrelativo.'","width=620,height=500");
			</script>';
		    
		    
	}
	
	public function mostrarPDFNotaventa($iIdNotaventa){
		$sLinkPDF = base_url()."tmp/Notaventa_".$iIdNotaventa.".pdf";
 		header ("Content-Disposition: attachment; filename=Notaventa_".$iIdNotaventa.".pdf\n\n");
 		header ("Content-Type: application/octet-stream");
 		header ("Content-Length: ".filesize($sLinkPDF));
 		readfile($sLinkPDF);
	}
	
	
}